﻿using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Security;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Update
{
    static class Program
    {
        const int BufferLength = 2048;
        const string FeedbackPath = MainWindow.OfficialWebsite + "/" + MainWindow.SoftwareName + "/Feedback";
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            Application.ThreadException += Application_ThreadException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainWindow());
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            handleException(e.ExceptionObject as Exception);
        }

        static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            handleException(e.Exception);
        }

        static void handleException(Exception ex)
        {
            if (ex is UnauthorizedAccessException || ex is SecurityException)
            {
                MessageBox.Show(Resources.Translate("PermissionDenied") + Environment.NewLine + ex.Message, Resources.Translate("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                DialogResult res = MessageBox.Show(string.Format(Resources.Translate("UnhandledExceptionPrompt"), Environment.NewLine), Resources.Translate("Ask"), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                switch (res)
                {
                    case DialogResult.Cancel:
                        Environment.Exit(-1);
                        break;
                    case DialogResult.No:
                        StringBuilder sb = new StringBuilder();
                        sb.AppendLine("Basic Information:");
                        sb.AppendLine("DateTime: " + DateTime.Now);
                        sb.AppendLine($"OS: {Environment.OSVersion.Platform} ({(Environment.Is64BitOperatingSystem ? "64bit" : "32bit")})");
                        sb.AppendLine("OS Version: " + Environment.OSVersion.VersionString);
                        sb.AppendLine("Processor Count: " + Environment.ProcessorCount);
                        sb.AppendLine("Primary Monitor Resolution: " + SystemInformation.PrimaryMonitorSize);
                        sb.AppendLine("Executable Path: " + Application.ExecutablePath);
                        sb.AppendLine();
                        sb.AppendLine("Exception Information:");
                        sb.AppendLine("Message: " + ex.Message);
                        sb.AppendLine("Source: " + ex.Source);
                        sb.AppendLine("StackTrace: " + ex.StackTrace);
                        try
                        {
                            WebClient wc = new WebClient();
                            string credPath = Path.Combine(MainWindow.TempPath, Guid.NewGuid().ToString());
                            wc.DownloadFile(FeedbackPath + "/credential", credPath);
                            string[] lns = File.ReadAllLines(credPath);
                            string logPath = Path.Combine(MainWindow.TempPath, Guid.NewGuid().ToString());
                            File.WriteAllText(logPath, sb.ToString());
                            FileInfo fi = new FileInfo(logPath);
                            FtpWebRequest req = WebRequest.Create("ftp://47.103.48.111:21/" + fi.Name + ".log") as FtpWebRequest;
                            req.UseBinary = true;
                            req.Credentials = new NetworkCredential(lns[0], lns[1]);
                            req.KeepAlive = req.UsePassive = false;
                            req.Proxy = null;
                            req.Method = WebRequestMethods.Ftp.UploadFile;
                            req.ContentLength = fi.Length;
                            byte[] buff = new byte[BufferLength];
                            FileStream fs = fi.OpenRead();
                            int contentlen;
                            Stream stream = req.GetRequestStream();
                            while ((contentlen = fs.Read(buff, 0, BufferLength)) != 0)
                            {
                                stream.Write(buff, 0, contentlen);
                            }
                            stream.Close();
                            fs.Close();
                            File.Delete(logPath);
                        }
                        catch (Exception ex2)
                        {
                            MessageBox.Show(ex2.Message, Resources.Translate("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        Environment.Exit(-1);
                        break;
                }
            }
        }
        public static void SwitchLanguage()
        {
            try
            {
                string code = File.ReadAllText("lang");
                Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(code);
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(code);
            }
            catch (Exception)
            {

            }
        }
        static Program()
        {
            SwitchLanguage();
        }
    }
}
